<script setup>
import VueBarcode from '@chenfengyuan/vue-barcode'
import { reactive, computed, onMounted, inject } from 'vue'
import { getStyles } from './index'
import { isTrueForDict } from '@/utils/dict.js'

const getNode = inject('getNode')
const nodeConfig = reactive({
  nodeData: {
    bar_height: 50,
    content_color: '#ffffff',
    human_readable_font_type: 'CODE128'
  },
  value: null,
  styles: null,
  isInit: false
})
const updateData = (nodeData) => {
  const {
    contentValue
  } = nodeData

  nodeConfig.styles = getStyles(nodeData)
  nodeConfig.value = contentValue
  nodeConfig.nodeData = nodeData
  nodeConfig.isInit = true
}
const options = computed(() => {
  return {
    format: nodeConfig.nodeData.humanReadableFontType || 'CODE128',
    height: nodeConfig.nodeData.barHeight,
    lineColor: nodeConfig.nodeData.contentColor,
    text: nodeConfig.value,
    displayValue: false,
    margin: 0
  }
})
onMounted(() => {
  const node = getNode()
  const nodeData = node.getData()
  updateData(nodeData)
  node.on('change:data', ({ current }) => {
    updateData(current)
  })
})
</script>

<template>
  <div
    class="w-full h-full overflow-hidden bar-code-node"
    :class="{ 'bar-code-node': isTrueForDict(nodeConfig.nodeData.autoScale) }"
    :style="nodeConfig.styles"
    v-if="nodeConfig.isInit"
  >
    <vue-barcode
      :value="nodeConfig.value"
      tag="img"
      :options="options"
    ></vue-barcode>
  </div>
</template>

<style lang="less" scoped>
.bar-code-node {
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
